package com.leen.admin.service.impl;

import com.leen.admin.dto.DeptDto;
import com.leen.admin.entity.Dept;
import com.leen.admin.repository.DeptRepository;
import com.leen.admin.service.DeptService;
import com.leen.common.vo.ResponseVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeptServiceImpl extends CurdServiceImpl<Dept,Integer> implements DeptService {

    private DeptRepository deptRepository;


    @Autowired
    public void setDeptRepository(DeptRepository deptRepository){
        this.deptRepository = deptRepository;
        //给父类赋值
        super.setCrudRepository(deptRepository);
    }
    @Override
    public ResponseVO search(DeptDto deptDto) {
        //分页页码
        Pageable pageable = PageRequest.of(deptDto.getPageNumber()-1,deptDto.getPageSize());
        //构建查询对象
        Specification<Dept> specification = new Specification<Dept>() {
            @Override
            public Predicate toPredicate(Root<Dept> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //创建一个Predicate的集合
                List<Predicate> arr = new ArrayList<>();
                if (StringUtils.isNotBlank(deptDto.getName())){
                    arr.add(criteriaBuilder.like(root.get("name"),"%"+deptDto.getName()+"%"));
                }
                if (deptDto.getStartTime()!=null && !deptDto.getStartTime().equals("")){
                    arr.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"),deptDto.getStartTime()));
                }

                if (deptDto.getEndTime()!=null && !deptDto.getEndTime().equals("")){
                    arr.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"),deptDto.getEndTime()));
                }
                return criteriaBuilder.and(arr.toArray(new Predicate[arr.size()]));
            }
        };
        //查询
        Page<Dept> page = this.deptRepository.findAll(specification,pageable);
        return new ResponseVO(page.getTotalElements(),page.getContent());
    }
}
